<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片转Base64编码</title>
    <link rel="stylesheet" href="../../bootstrap/bootstrap.min.css">
    <style>
        label {
            font-weight: bold;
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <h1 class="mb-4">图片转Base64编码</h1>
        <form>
            <div class="mb-3">
                <label for="imageFile" class="form-label">请选择要转换的图片文件：</label>
                <input class="form-control" type="file" id="imageFile" accept=".jpeg,.jpg,.png,.gif,.bmp,.svg,.webp,.tif,.tiff">
            </div>
            <button type="button" class="btn btn-primary" onclick="convertToBase64()">转换</button>
        </form>
        <div class="mt-4">
            <label for="base64Text" class="form-label">Base64编码结果：</label>
            <textarea class="form-control" id="base64Text" rows="10"></textarea>
        </div>
    </div>
    <script>
        function convertToBase64() {
            const fileInput = document.getElementById("imageFile");
            const file = fileInput.files[0];
            if (!file) {
                alert("请先选择要转换的图片文件！");
                return;
            }

            const reader = new FileReader();
            reader.onload = function () {
                let base64Text = reader.result.split(",")[1];
                const fileType = file.type.split("/")[1];  // extract file type (e.g. "png")
                base64Text = `data:image/${fileType};base64,${base64Text}`;  // add prefix
                document.getElementById("base64Text").value = base64Text;
            };
            reader.readAsDataURL(file);
        }
    </script>
</body>

</html>
